package com.it.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.dao.BlogTypeMapper;
import com.it.domain.BlogTypeEntity;
import com.it.exception.NotFoundException;
import com.it.service.BlogTypeService;
import com.it.util.PageUtils;
import com.it.util.Query;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


/**
 * @author : code1997
 * @date : 2021/9/9 22:46
 */
@Service
public class BlogTypeServiceImpl extends ServiceImpl<BlogTypeMapper, BlogTypeEntity> implements BlogTypeService {

    @Transactional
    @Override
    public BlogTypeEntity saveType(BlogTypeEntity blogTypeEntity) {
        this.baseMapper.insert(blogTypeEntity);
        return blogTypeEntity;
    }

    @Transactional
    @Override
    public BlogTypeEntity getType(Long id) {
        return this.baseMapper.selectById(id);
    }


    @Override
    public PageUtils listType(Map<String, Object> params) {
        return new PageUtils(this.page(new Query<BlogTypeEntity>().getPage(params, "id", false), new QueryWrapper<>()));
    }

    @Override
    public List<BlogTypeEntity> listType() {
        return this.baseMapper.selectList(new QueryWrapper<>());
    }

    /**
     * todo:求blogs数量为前size名的blogs
     */
    @Override
    public List<BlogTypeEntity> listTypeTop(Integer size) {
        return this.baseMapper.listTypeTop(size);
    }

    @Transactional
    @Override
    public BlogTypeEntity updateType(Long id, BlogTypeEntity blogTypeEntity) {
        //可以安全的判断对象是否存在，避免空的出现
        BlogTypeEntity tempBlogTypeEntity = this.baseMapper.selectById(id);
        if (tempBlogTypeEntity == null) {
            throw new NotFoundException("该类型不存在！更新失败！！！");
        }
        BeanUtils.copyProperties(blogTypeEntity, tempBlogTypeEntity);
        this.baseMapper.updateById(blogTypeEntity);
        return blogTypeEntity;
    }

    @Transactional
    @Override
    public void deleteType(Long id) {
        this.baseMapper.deleteById(id);
    }

    @Transactional
    @Override
    public BlogTypeEntity getTypeByName(String name) {
        return this.baseMapper.selectOne(new QueryWrapper<BlogTypeEntity>().eq("name", name));
    }
}
